import axios from 'axios'
import {useUserStore} from '@/stores'
import {ElMessage} from 'element-plus'
import router from '@/router/index.js'

const baseURL = 'http://119.91.249.251:8081/api/private/v1'

const instance = axios.create({
    baseURL,
    timeout: 10000
})

//请求拦截器
instance.interceptors.request.use(
    (config) => {
        const userStore = useUserStore()
        if (userStore.user.token) {
            config.headers.Authorization = userStore.user.token
        }
        return config
    },
    (err) => Promise.reject(err)
)

//响应拦截器
instance.interceptors.response.use(
    (res) => {
        if ((res.data.meta.status === 200) || (res.data.meta.status === 201) || (res.data.meta.status === 204)) {
            // ElMessage.success(res.data.meta.msg)
            return res.data.data
        }
        ElMessage.error(res.data.message || '服务异常')
        return Promise.reject(res.data)
    },
    (err) => {
        if (err.response?.status === 401) {
            router.push('/login')
        }
        ElMessage.error(err.response.data.message || '服务异常')
        return Promise.reject(err)
    }
)

export default instance
export {baseURL}
